# -*- coding: utf-8 -*-
# @Time : 2021/02/22
# @Author : ricky
# @File : configini.py
# @Software: vscode
"""
系统配置类
"""
import configparser
import os
from . import aescrypt
from . import path


class Config:
    """
    系统配置类
    """

    # 敏感属性
    __SENSITIVE_TUPLE = ('password', 'pass', 'pwd')

    def __init__(self, filepath=None):
        if filepath:
            self.configPath = filepath
        else:
            self.configPath = path.resource_path('config.ini')
        self.config_parser = configparser.ConfigParser()
        if not os.path.exists(self.configPath):
            self.config_parser['config'] = {'enable': False}
            self.write()
        self.config_parser.read(self.configPath, encoding="utf-8")
        self.crypt = aescrypt.AesCrypt()

    def get_value(self, section, key):
        """
        根据section和key获取value

        参数:
            section: 节点
            key: 键
        返回:
            value: 值
        """
        if not self.config_parser.has_section(section):
            return ''
        value = self.config_parser.get(section, key)
        if key in self.__SENSITIVE_TUPLE:
            value = self.crypt.decrypt(value)
        return value.replace('\n', '')

    def get_dict(self):
        """
        获取配置字典

        返回:
            字典类型数据
        """
        d = {}
        sections = self.config_parser.sections()
        for s in sections:
            items = self.config_parser.items(s)
            for item in items:
                k = item[0]
                v = item[1]
                if k in self.__SENSITIVE_TUPLE:
                    v = self.crypt.decrypt(v)
                d[s + '.' + k] = v.replace('\n', '')
        return d

    def set_value(self, section, key, value):
        """
        根据section和key设置value

        参数：
            section: 节点
            key: 键
            value: 值
        """
        if not self.config_parser.has_section(section):
            self.config_parser.add_section(section)
        if key in self.__SENSITIVE_TUPLE:
            value = self.crypt.encrypt(value).replace('\n', '')
        self.config_parser.set(section, key, value)

    def write(self):
        """写入配置文件"""
        with open(self.configPath, 'w+') as configFile:
            self.config_parser.write(configFile)
